package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CmbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cmbc.ebank.CmbcB2bMessage;
import com.gopay.common.domain.bank.cmbc.ebank.CmbcMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

public class CheckOrderCmbcB2bImpl implements BankOrderService {
	private final static Logger logger = LoggerFactory.getLogger("CMBC");

	@Resource(name = "bankClient")
	private BankInteractRemoteService bankClient;
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());
		try {

			CmbcB2bMessage base = new CmbcB2bMessage();
			base.setOrderId(bankOrder.getOrderId());
			base.setBankOrderId(bankOrder.getOutOrderId());
			base.setBank(BankConstants.BANK_LOGO_CMBC);
			base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
			base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
			base.setMerchantTrnxNo(bankOrder.getOutOrderId());
			base.setTrnxCode(CmbcConstants.QUERYORDER_BUSINESS_CODE);
			Result result = new Result();
			result = bankClient.query(base);

			if (result == null || !result.isSuccess()) {
				logger.error("bankClient fail.");
				if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
					checkOrderResult.setCommunicateError(true);
				}
				logger.error(ToStringBuilder.reflectionToString(result,ToStringStyle.DEFAULT_STYLE));
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}
			CmbcMessage response = null;
			if (result != null && result.isSuccess()) {
				response = (CmbcMessage) result.getDefaultModel();
			}
			String outOrderId = bankOrder.getOrderId();
			// 返回结果为null
			if (response == null) {
				logger.error("民生银行B2B 对账失败，订单查询返回结果为null，orderId：" + outOrderId);
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
			}
			if (!CmbcConstants.RES_CODE_SUCCESS.equalsIgnoreCase(response.getResCode())) { // 如果查询本身失败，跳过这一笔
				logger.error("民生B2B订单" + outOrderId + "交易查询失败,错误内容: "+ response.getResMessage());
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg(response.getResMessage());
			} else {
				// 如果查询成功，则一定有定单信息
				if (!(CmbcConstants.ORDER_STATE_SUCCESS.equalsIgnoreCase(response.getOrderStatus()) || CmbcConstants.ORDER_STATE_FAILE.equalsIgnoreCase(response.getOrderStatus()))) { // 如果状态未明
					logger.error("民生B2B订单" + outOrderId + "交易结果未明确");
					checkOrderResult.setErrMsg("银行返回交易未明确");
				} else {
					// 状态明确，成功或失败
					if (CmbcConstants.ORDER_STATE_SUCCESS.equalsIgnoreCase(response.getOrderStatus())) {// 如果成功
						logger.info("民生B2B订单" + outOrderId + "的交易成功");
						checkOrderResult.setSuccess(true);
						InAccInfo accInfo = new InAccInfo();
						accInfo.setOrderId(bankOrder.getOrderId());
						accInfo.setAmount(new BigDecimal(response.getOrderAmt()));
						accInfo.setRetCode("00");
						accInfo.setCardType(BankCardType.Unknown.toString());
						checkOrderResult.setAccInfo(accInfo);
					} else {// 如果失败
						checkOrderResult.setBankFailure(true);
						logger.info("民生B2B订单" + outOrderId + "的交易失败");
						checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
						checkOrderResult.setErrMsg("银行返回交易失败");
					}

				}
			}
			return checkOrderResult;
		} catch (Exception e) {
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("对账调用bis失败");
			return checkOrderResult;
		}

	}
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}
}
